

import 'package:date_format/date_format.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:month_picker_dialog/month_picker_dialog.dart';
// import 'package:month_picker_dialog/month_picker_dialog.dart';
// import 'package:month_year_picker/month_year_picker.dart';
import 'package:smart_freezer/core/model/warn_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/result_data.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';

import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';

import '../../../generated/locale_keys.g.dart';
// import 'package:smart_freezer/core/utils/month_date_picker/src/dialogs.dart';

class HomeWarnInfo extends StatefulWidget {
  const HomeWarnInfo({Key? key}) : super(key: key);

  @override
  State<HomeWarnInfo> createState() => _HomeWarnInfoState();
}

class _HomeWarnInfoState extends State<HomeWarnInfo> {

  List<WarnInfoModel> _dataList = [];
  int currentPage = 0;

  String _chooseDate = "";
  String _msgCount = "0";

  // 0-T1探头故障, 1-T2探头故障, 2-T3探头故障, 3-温度超上限报警, 4-温度超下限报警, 5-开门报警, 6-冷凝器清洁报警
  final warnInfoList = [
    {"title": LocaleKeys.device_info_warn_t1.trc(), "icon": IconNames.warn_t2},
    {"title": LocaleKeys.device_info_warn_t2.trc(), "icon": IconNames.warn_t2},
    {"title": LocaleKeys.device_info_warn_t1.trc(), "icon": IconNames.warn_t2},
    {"title": LocaleKeys.device_info_warn_up.trc(), "icon": IconNames.warn_wendu_up},
    {"title": LocaleKeys.device_info_warn_down.trc(), "icon": IconNames.warn_wendu_bottom},
    {"title": LocaleKeys.device_info_warn_door.trc(), "icon": IconNames.warn_open},
    {"title": LocaleKeys.device_info_warn_lengningqi.trc(), "icon": IconNames.warn_ice_clear},
  ];

  /// 获取已经产生报警信息的月份列表
  List<DateTime> _tagList = [];

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  String _productId = Get.arguments as String;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _chooseDate = formatDate(DateTime.now(), [yyyy, '-', mm]);
    _getNewList();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 1,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(LocaleKeys.other_warn_info.trc(), ),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        // color: Colors.white,
        child: Column(
          children: [
            Container(
              color: isDarkMode ? Color(0xFF33333A) : Color(0xFFF7F7F7),
              height: 44,
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(LocaleKeys.device_info_warn_info.trc(args: [_msgCount])),

                  Container(),
                  // InkWell(
                  //   onTap: () {
                  //     _getWarnInfoTagList();
                  //   },
                  //   child: Container(
                  //     decoration: BoxDecoration(
                  //       color: Color(0xFFEFF0F1),
                  //       borderRadius: BorderRadius.circular(15),
                  //     ),
                  //     height: 30,
                  //     padding: EdgeInsets.symmetric(horizontal: 10),
                  //     child: Row(
                  //       children: [
                  //         Text("$_chooseDate", style: TextStyle(color: Colors.grey),),
                  //         Icon(Icons.arrow_drop_down, color: Colors.grey, size: 16,),
                  //       ],
                  //     ),
                  //   ),
                  // ),
                ],
              ),
            ),

            Expanded(
              child: EasyRefresh.custom(
                  header: MaterialHeader(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  footer: MaterialFooter(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                  firstRefresh: true,
                  emptyWidget: _dataList.isEmpty ? Center(
                    child: Column(
                      children: [
                        SizedBox(height: 50,),
                        Image.asset(IconNames.home_w06, width: MainCommon.screenWidth * 0.6,),
                        Text(LocaleKeys.other_no_data.trc(), style: TextStyle(color: Colors.grey),),
                      ],
                    ),
                  ) : null,
                  slivers: [
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                              (context, index) {

                                final warnModel = _dataList[index];
                                final title = warnInfoList[warnModel.type]["title"] ?? "";
                                final icon = warnInfoList[warnModel.type]["icon"] ?? "";

                            return Container(
                              color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                              constraints: BoxConstraints(
                                minHeight: 60,
                              ),
                              child: Row(
                                children: [
                                  SizedBox(width: 20,),
                                  Image.asset(icon, width: 40,),
                                  SizedBox(width: 10,),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text("${title}", style: TextStyle(fontSize: 18),),
                                        Text("${warnModel.createTime}", style: TextStyle(color: Colors.grey, fontSize: 14),),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        childCount: _dataList.length,
                      ),
                    ),
                  ],
                onLoad: () async {
                    _getMoreList();
                },
                onRefresh: () async {
                    _getNewList();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  _getNewList() {
    _dataList = [];
    currentPage = 1;
    _getWarnInfoList(currentPage);
  }
  _getMoreList(){
    currentPage += 1;
    _getWarnInfoList(currentPage);
  }

  // 获取报警消息
  _getWarnInfoList(int page) async {

    final params = {"page": "$page", "limit": "20", "productId": _productId, "yearMonth": "",};
    ResultData data = await AppApi.getInstance().getWarnList(params);
    if(data.code == 0){
      _msgCount = data.data["messageCount"];
      final list = data.data["list"] as List;
      final modelList = list.map((e) => WarnInfoModel.fromJson(e)).toList();

      if(page == 1){
        _dataList = modelList;
      }else{
        _dataList.addAll(modelList);
      }
      _dataList.sort((left, right) => right.createTime.compareTo(left.createTime));

      setState(() {});
    }else {
      SmartDialog.showToast(data.msg);
    }

  }

  _getWarnInfoTagList() async {
    SmartDialog.showLoading();

    List<DateTime> timeList = [];
    for(int i = 1; i <= 12; i++) {
      final time = DateTime(DateTime.now().year, i);
      String timeStr = formatDate(time, [yyyy, '-', mm]);

      final params = {"page": "1", "limit": "1", "yearMonth": timeStr};
      ResultData data = await AppApi.getInstance().getWarnList(params);
      if(data.code == 0){
        int msgCount = int.tryParse(data.data["messageCount"].toString()) ?? 0;
        if(msgCount > 0) {
          timeList.add(time);
        }
      }
    }

    if(timeList.isNotEmpty) {
      SmartDialog.dismiss();
      _chooseTime(timeList);
    }else{
      _chooseTime(null);
    }

  }

  // 选择时间
  _chooseTime(List<DateTime>? timeList) async {

    logs("timeList: $timeList");

    showMonthPicker(
      context: context,
      firstDate: DateTime(DateTime.now().year - 5, 1),
      lastDate: DateTime.now(),
      initialDate: DateTime.now(),
      locale: context.locale, //Locale("zh"),
      tagDateList: timeList,
    ).then((date) {
      if (date != null) {
        _chooseDate = formatDate(date, [yyyy, '-', mm]);
        _getNewList();
      }
    });
  }


}
